package br.com.JogoMemo;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Player;
import dao.banco.DaoPlayer;

/**
 * Servlet implementation class Jogo
 */
@WebServlet("/Jogo")
public class Jogo extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String playerAdded;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Jogo() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			catchPlayer(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter(); 
		out.println(playerAdded);
	}

	protected void catchPlayer(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		PrintWriter out = response.getWriter(); 
		Player player = new Player();
		DaoPlayer daoplayer = new DaoPlayer();
		
		player.setName(request.getParameter("name"));
       
		try {
			
			playerAdded = player.getName();
			daoplayer.adiciona(player);
			
			out.println("<p>Funfou! Adicionado: "+playerAdded+"</p>");
		} catch (Exception e) {
			 out.println("<p>Funfou! Adicionado: "+playerAdded+"</p>");  
	            throw new Exception (e.getMessage());
			
		} 
			 

	}

}
